package main

import (
	"math/rand"
	"time"

	"bufio"
	"os"

	"weibo"
)

//针对 http://login.sina.com.cn
func main() {
	weibo.SetLogLevel(0)

	print("输入1转发，否则不转发： ")
	reader := bufio.NewReader(os.Stdin)
	b, _, _ := reader.ReadLine()
	if string(b) == "1" {
		weibo.Param_forward = "1"
	}

	processors := weibo.GetProcessors()

	//串行login
	for _index, proc := range processors {
		if ps := weibo.GetPS(); len(ps[_index]) >= 3 {
			_time, _ := time.ParseInLocation("2006-01-02 15:04:05", ps[_index][2], time.Local) //parse是解析UTC的
			ti := _time.Add(3 * time.Hour)
			if time.Now().Before(ti) {
				continue
			}
		}

		servertime, nonce, pubkey, rsakv := proc.Get_preLogin()
		username, password := proc.Encode(servertime, nonce, pubkey)
		proc.Login(servertime, nonce, rsakv, pubkey, username, password, "")

		proc.SignIn()
		mids := get_mids(proc)
		send(proc, mids)

		proc.Logout()
		sleep(3 * time.Second)
		//proc.HotPoint()
	}

	//并发do
	//for _, proc := range processors {
	//	go do(proc)
	//}

	time.Sleep(10 * time.Hour)
}

//最好一下子刷<25条微博
//最好一下子转发<14条
func get_mids(proc *weibo.Processor) map[string]bool {
	i := 0
	mids := make(map[string]bool) //key不重复
	for page := 1; page < 3; page++ {
		tmp := proc.GetMid(page)
		for _, mid := range tmp {
			if i > 24 {
				break
			}
			mids[mid] = true
			i++
		}
	}
	weibo.Info("mid: ", mids)
	weibo.Info("mid len: ", len(mids))
	return mids
}

func send(proc *weibo.Processor, mids map[string]bool) {
	for mid := range mids {
		time.Sleep(time.Duration(30+rand.Intn(10)) * time.Second) //不要固定间隔，模仿人类
		is_del := proc.Like(mid)
		if is_del == 1 { //0为点赞，1为取消
			proc.Like(mid)
		}
		comment := proc.GetComment(mid)
		proc.SendComment(mid, comment)
	}
}

func do(proc *weibo.Processor) {
	proc.SignIn()

	for {
		mids := get_mids(proc)
		send(proc, mids)

		sleep(30 * time.Minute)
	}

}

func sleep(duration time.Duration) {
	for ; duration > 0; duration = duration - 3*time.Second {
		print("\r waiting... ", duration.String())
		time.Sleep(3 * time.Second)
	}
}
